package org.eleorc.resources.builtinresource;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

public class UrlResourceDem {

    public static void main(String[] args) throws MalformedURLException {
        // 构造一个UrlResource实例，指向一个网络图片资源
        String imageUrl = "https://wanx.alicdn.com/wanx/1160207083303852/text_to_image/75d2108374504093877994c62e8118f4_1.png";
        Resource resource = new UrlResource(imageUrl);

        try {
            // 检查资源是否存在
            if (resource.exists()) {
                System.out.println("资源存在");

                // 使用Spring的IOUtils工具类将输入流保存到本地文件
                File destinationFile = new File("D:\\test1.png");

                try (InputStream inputStream = resource.getInputStream();
                     FileOutputStream outputStream = new FileOutputStream(destinationFile)) {

                    StreamUtils.copy(inputStream, outputStream);
                    System.out.println("文件已成功保存到 " + destinationFile.getAbsolutePath());
                    inputStream.close();
                }
                // 记得关闭输入流
            } else {
                System.out.println("资源不存在");
            }
        } catch (IOException e) {
            System.err.println("读取资源时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
